import React from "react"
import $ from "jquery"
import Switch from "@material-ui/core/Switch"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faMinusCircle } from "@fortawesome/free-solid-svg-icons"
import {
	CONSTANTS,
	PATTERN_EMAIL,
	PATTERN_PASS,
	STYLES,
	PAY_ICON_URL,
	EXCHANGE_ICON_URL,
	CURRENCY_ICON_URL,
} from "../constants"
import {
	ICreateUserModal,
	IAddNewExchangeModal,
	IAddNewCurrencyModal,
	IAddNewPayMethodModal,
	IAddNewOrderStatusModal,
	IAddNewSubAccountModal,
	IEditPassUserModal,
	IEditProfileUserModal,
	IPasswordResetModal,
	IEditOrderModal,
	IEditPaymentItemModal,
	IEditExchangeItemModal,
	IEditCurrencyItemModal,
	IEditUserPayTypesModal,
	IEditOrderStatusModal,
	IEditAdvModal,
	IInsertBalanceModal,
} from "../types"
import {
	isValideField,
	getLocalDate,
	startModalAlert,
	getUrlIcon,
	getPriceMasked,
	getValuationUSDT,
	getCostUSDT,
	getSummUSDT,
	getUserPropertyByExchange,
	getArraySortedByProp,
} from "../common"

import "../styles/UserModal.css"

// Создание нового юзера
export const CreateUserModal: React.FC<ICreateUserModal> = props => {
	return (
		<div
			className="modal fade"
			id="modal-addUser"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modal-addUser"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className="modal-header alert-danger">
						<h5 className="modal-title">Registration</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="form-label-group text-left">
							<label htmlFor="inputEmail">Enter email</label>
							<input
								onChange={(ev: any) => {
									const pattern = PATTERN_EMAIL
									isValideField(ev.target.id, pattern)
								}}
								type="email"
								id="inputEmail"
								className="form-control"
								placeholder="your@mail.com"
								required
								autoFocus
							/>
							<div className="invalid-feedback">{CONSTANTS.FEEDBACK_EMAIL}</div>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="inputPassword">Enter Password</label>
							<input
								type="password"
								id="inputPassword"
								className="form-control"
								placeholder="enter Password"
								required
								onChange={(ev: any) => {
									const pattern = PATTERN_PASS
									isValideField(ev.target.id, pattern)
								}}
							/>
							<div className="invalid-feedback">{CONSTANTS.FEEDBACK_PASS}</div>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="repeatPassword">Repeat Password</label>
							<input
								onChange={(ev: any) => {
									const pattern = PATTERN_PASS
									isValideField(ev.target.id, pattern)
								}}
								type="password"
								id="repeatPassword"
								className="form-control"
								placeholder="repeat Password"
								required
							/>
							<div className="invalid-feedback">{CONSTANTS.FEEDBACK_PASS}</div>
						</div>

						<button
							name="addUser"
							onClick={(ev: any) => {
								const login = $("#inputEmail").val()
								const pass = $("#inputPassword").val()
								const repeat = $("#repeatPassword").val()
								if (login !== "" && pass !== "" && pass === repeat) {
									const objUser = {
										inputEmail: login,
										inputPassword: pass,
									}
									props.validateForm(objUser, ev.target.name)
									$("#inputEmail").val("")
									$("#inputPassword").val("")
									$("#repeatPassword").val("")
								} else {
									props.handlerPopupWindow(
										STYLES.WARNING,
										CONSTANTS.PASS_NOT_COINCIDE
									)
									startModalAlert()
								}
							}}
							className="btn btn-info btn-block mt-3"
							type="button"
						>
							Save
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Добавление нового p2p-сервиса
export const AddNewExchangeModal: React.FC<IAddNewExchangeModal> = props => {
	const { userId, insertNewItemToDB, handlerPopupWindow } = props

	const storageProps = {
		nameExchange: "",
		shortName: "",
	}
	const [objProps, handlerProps] = React.useState(storageProps)

	return (
		<div
			className="modal fade"
			id="modal-addNewExchange"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modal-addNewExchange"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className="modal-header alert-danger">
						<h5 className="modal-title">Add New Exchange</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="form-label-group text-left">
							<label htmlFor="nameExchange">Name Exchange</label>
							<input
								type="text"
								name="nameExchange"
								className="form-control"
								placeholder="Enter Name Exchange"
								value={objProps.nameExchange === null ? "" : objProps.nameExchange}
								onChange={(ev: any) => {
									handlerProps({
										...objProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="shortNameExchange">shortName Exchange</label>
							<input
								type="text"
								name="shortName"
								className="form-control"
								placeholder="enter shortName Exchange"
								value={objProps.shortName === null ? "" : objProps.shortName}
								onChange={(ev: any) => {
									handlerProps({
										...objProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>

						<button
							name="addNewExchange"
							className="btn btn-info btn-block mt-3"
							disabled={objProps.nameExchange === "" || objProps.shortName === ""}
							type="button"
							onClick={() => {
								if (objProps.nameExchange !== "" && objProps.shortName !== "") {
									const objParams = {
										userId,
										typeItem: "addNewExchange",
										objItem: {
											fullNameExchange: objProps.nameExchange,
											shortNameExchange: objProps.shortName.toUpperCase(),
										},
									}
									insertNewItemToDB(objParams)
									// console.log(objParams)
									handlerProps({
										nameExchange: "",
										shortName: "",
									})
									$("#modal-addNewExchange").modal("hide")
								} else {
									handlerPopupWindow(STYLES.WARNING, CONSTANTS.FIELDS_FULL)
									startModalAlert()
								}
							}}
						>
							Add New Exchange
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Добавление нового вида крипты / фиата
export const AddNewCurrencyModal: React.FC<IAddNewCurrencyModal> = props => {
	const { userId, insertNewItemToDB, handlerPopupWindow } = props

	const storageProps = {
		currency: "", // USDT, BTC, RUB, GBP
		currencyName: "", // bitcoin, etherium
		currencyType: "", // ['coin', 'fiat']
		symbol: "", // "₽", "$"
		iconUrl: ".png", // `RUB.png`
		tickerUSDT: "", // `ETHUSDT.png`
	}
	const [objProps, handlerProps] = React.useState(storageProps)

	return (
		<div
			className="modal fade"
			id="modal-addNewCurrency"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modal-addNewCurrency"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className="modal-header alert-danger">
						<h5 className="modal-title">Add New Currency</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="form-label-group text-left">
							<label htmlFor="nameExchange">Currency</label>
							<input
								type="text"
								name="currency"
								className="form-control"
								placeholder="Enter Ticker Currency"
								value={objProps.currency === null ? "" : objProps.currency}
								onChange={(ev: any) => {
									handlerProps({
										...objProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="iconUrl">Icon Currency</label>
							<input
								type="text"
								name="iconUrl"
								className="form-control"
								placeholder="enter Icon Currency"
								value={objProps.iconUrl === null ? "" : objProps.iconUrl}
								onChange={(ev: any) => {
									handlerProps({
										...objProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="iconUrl">Type Currency</label>
							<select
								name="currencyType"
								className="custom-select mr-1"
								onChange={(ev: any) => {
									handlerProps({
										...objProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							>
								<option value="">Choose Type</option>
								<option value="coin">Coin Currency</option>
								<option value="fiat">Fiat Currency</option>
							</select>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="iconUrl">tickerUSDT</label>
							<input
								type="text"
								name="tickerUSDT"
								className="form-control"
								placeholder="enter Currency tickerUSDT"
								value={objProps.tickerUSDT === null ? "" : objProps.tickerUSDT}
								onChange={(ev: any) => {
									handlerProps({
										...objProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>

						<button
							name="addNewCurrency"
							className="btn btn-info btn-block mt-3"
							disabled={
								objProps.currency === "" ||
								objProps.iconUrl === "" ||
								objProps.currencyType === "" ||
								objProps.tickerUSDT === ""
							}
							type="button"
							onClick={() => {
								if (objProps.currency !== "") {
									const objParams = {
										userId,
										typeItem: "addNewCurrency",
										//  typeItem: "addGroupCurrency",
										objItem: {
											...objProps,
											currency: objProps.currency.toUpperCase(),
											tickerUSDT: objProps.tickerUSDT.toUpperCase(),
										},
									}
									insertNewItemToDB(objParams)
									// console.log(objParams)
									handlerProps({
										currency: "",
										currencyName: "",
										currencyType: "",
										symbol: "",
										iconUrl: ".png",
										tickerUSDT: "",
									})
									$("#modal-addNewCurrency").modal("hide")
								} else {
									handlerPopupWindow(STYLES.WARNING, CONSTANTS.FIELDS_FULL)
									startModalAlert()
								}
							}}
						>
							Add New Currency
						</button>

						{/* <button
							name="addGroupCurrency"
							className="btn btn-success btn-block mt-3"
							// disabled={}
							type="button"
							onClick={() => {
								const objParams = {
									userId,
									typeItem: "addGroupCurrency",
									objItem: {},
								}
								insertNewItemToDB(objParams)
								$("#modal-addNewCurrency").modal("hide")
							}}
						>
							addGroupCurrency
						</button> */}
					</div>
				</div>
			</div>
		</div>
	)
}

// Добавление нового платежного метода
export const AddNewPayMethodModal: React.FC<IAddNewPayMethodModal> = props => {
	const { userId, insertNewItemToDB, handlerPopupWindow } = props

	const storageProps = {
		payTypeName: "",
		iconUrlColor: ".png",
	}
	const [objProps, handlerProps] = React.useState(storageProps)

	return (
		<div
			className="modal fade"
			id="modal-addNewPayType"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modal-addNewPayType"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className="modal-header alert-danger">
						<h5 className="modal-title">Add New PayType</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						{/* PayTypeName */}
						<div className="form-label-group text-left">
							<label htmlFor="payTypeName">PayType Name</label>
							<input
								type="text"
								id="payTypeName"
								name="payTypeName"
								className="form-control"
								placeholder="Enter PayType Name"
								value={objProps.payTypeName === null ? "" : objProps.payTypeName}
								onChange={(ev: any) => {
									handlerProps({
										...objProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>
						{/* iconUrlColor */}
						<div className="form-label-group text-left">
							<label htmlFor="iconUrlColor">iconUrlColor</label>
							<input
								type="text"
								id="iconUrlColor"
								name="iconUrlColor"
								className="form-control"
								placeholder="enter Icon PayType"
								value={objProps.iconUrlColor === null ? "" : objProps.iconUrlColor}
								onChange={(ev: any) => {
									handlerProps({
										...objProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>

						<button
							name="addNewPayType"
							className="btn btn-info btn-block mt-3"
							disabled={
								objProps.payTypeName === "" || objProps.iconUrlColor === ".png"
							}
							type="button"
							onClick={() => {
								if (objProps.payTypeName !== "") {
									const objParams = {
										userId,
										typeItem: "addNewPayType",
										objItem: {
											payType: objProps.payTypeName.trim(),
											iconUrlColor: objProps.iconUrlColor.trim(),
										},
									}
									insertNewItemToDB(objParams)
									// console.log(objParams)
									handlerProps({
										payTypeName: "",
										iconUrlColor: ".png",
									})
									$("#modal-addNewPayType").modal("hide")
								} else {
									handlerPopupWindow(STYLES.WARNING, CONSTANTS.FIELDS_FULL)
									startModalAlert()
								}
							}}
						>
							Add New PayType
						</button>

						{/* <button
							name="addGroupPayType"
							className="btn btn-success btn-block mt-3"
							disabled
							type="button"
							onClick={() => {
								const objParams = {
									userId,
									// typeItem: "unsetFieldPayMethod",
									typeItem: "addGroupOrderStatus",
									objItem: {},
								}
								insertNewItemToDB(objParams)
								$("#modal-addNewPayType").modal("hide")
							}}
						>
							unsetPayType
						</button> */}
					</div>
				</div>
			</div>
		</div>
	)
}

// Добавление нового OrderStatus
export const AddNewOrderStatusModal: React.FC<IAddNewOrderStatusModal> = props => {
	return <div>AddNewOrderStatusModal</div>
}

// Добавление нового платежного subAccount
export const AddNewSubAccountModal: React.FC<IAddNewSubAccountModal> = props => {
	const {
		userId,
		// insertNewItemToDB,
		handlerPopupWindow,
	} = props

	const storageProps = {
		nameExchange: "",
		shortName: "",
	}
	const [objProps, handlerProps] = React.useState(storageProps)

	return (
		<div
			className="modal fade"
			id="modal-addNewSubAccount"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modal-addNewSubAccount"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className="modal-header alert-danger">
						<h5 className="modal-title">Add New SubAccounte</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="form-label-group text-left">
							<label htmlFor="nameExchange">Enter Name Exchange</label>
							<input
								type="text"
								name="nameExchange"
								className="form-control"
								placeholder="Enter Name Exchange"
								value={objProps.nameExchange === null ? "" : objProps.nameExchange}
								onChange={(ev: any) => {
									handlerProps({
										...objProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="shortNameExchange">Enter shortName Exchange</label>
							<input
								type="text"
								name="shortName"
								className="form-control"
								placeholder="enter shortName Exchange"
								value={objProps.shortName === null ? "" : objProps.shortName}
								onChange={(ev: any) => {
									handlerProps({
										...objProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>

						<button
							name="addNewSubAccount"
							className="btn btn-info btn-block mt-3"
							disabled={objProps.nameExchange === "" || objProps.shortName === ""}
							type="button"
							onClick={() => {
								if (objProps.nameExchange !== "" && objProps.shortName !== "") {
									const objParams = {
										userId,
										typeItem: "addNewSubAccount",
										objItem: {
											fullNameExchange: objProps.nameExchange,
											shortNameExchange: objProps.shortName,
										},
									}
									// insertNewItemToDB(objParams)
									console.log(objParams)
									handlerProps({
										nameExchange: "",
										shortName: "",
									})
									$("#modal-addNewSubAccount").modal("hide")
								} else {
									handlerPopupWindow(STYLES.WARNING, CONSTANTS.FIELDS_FULL)
									startModalAlert()
								}
							}}
						>
							Add SubAccount
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Редактирование пароля
export const EditPassUserModal: React.FC<IEditPassUserModal> = props => {
	const { userProfile } = props
	return (
		<div
			className="modal fade"
			id="modal-editPassUser"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="exampleModalCenterTitle"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className="modal-header alert-danger">
						<h5 className="modal-title">Editor User Pass</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="form-label-group text-left">
							<label htmlFor="inputOldPass">Enter Old Password</label>
							<input
								type="password"
								id="inputOldPass"
								className="form-control"
								placeholder="enter Old Password"
								required
								autoFocus
								onChange={(ev: any) => {
									const pattern = PATTERN_PASS
									isValideField(ev.target.id, pattern)
								}}
							/>
							<div className="invalid-feedback">{CONSTANTS.FEEDBACK_PASS}</div>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="inputNewPass">Enter New Password</label>
							<input
								type="password"
								id="inputNewPass"
								className="form-control"
								placeholder="enter New Password"
								required
								onChange={(ev: any) => {
									const pattern = PATTERN_PASS
									isValideField(ev.target.id, pattern)
								}}
							/>
							<div className="invalid-feedback">{CONSTANTS.FEEDBACK_PASS}</div>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="repeatNewPass">Repeat New Password</label>
							<input
								type="password"
								id="repeatNewPass"
								className="form-control"
								placeholder="repeat New Password"
								required
								onChange={(ev: any) => {
									const pattern = PATTERN_PASS
									isValideField(ev.target.id, pattern)
								}}
							/>
							<div className="invalid-feedback">{CONSTANTS.FEEDBACK_PASS}</div>
						</div>
						<button
							name="editPassUser"
							onClick={(ev: any) => {
								const oldPass = $("#inputOldPass").val()
								const newPass = $("#inputNewPass").val()
								const repeat = $("#repeatNewPass").val()
								if (oldPass !== "" && newPass !== "" && newPass === repeat) {
									const objUser = {
										fieldChangeable: "changePassword",
										id: userProfile.id,
										// nickName: userProfile.nickName,
										// binanceId: userProfile.binanceId,
										// lang: userProfile.lang,
										// theme: userProfile.theme,
										inputOldPass: oldPass,
										inputNewPass: newPass,
										repeatNewPass: repeat,
									}
									props.validateForm(objUser, ev.target.name)
								}
							}}
							className="btn btn-info btn-block mt-3"
							type="button"
						>
							Save Changes
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Редактирование nickName / userExchangeId
export const EditProfileUserModal: React.FC<IEditProfileUserModal> = props => {
	const { userProfile, dataConstants, getListOption, validateForm } = props
	const [objUser, updateObjUser] = React.useState({
		exchange: "",
		fieldChangeable: "updateProfile",
		id: userProfile.id,
		exchangeUserId: "",
		userNickName: "",
	})
	const listExchanges = getListOption(
		dataConstants.exchanges,
		"listExchanges"
	)

	return (
		<div
			className="modal fade"
			id="modal-editProfileUser"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="exampleModalCenterTitle"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className="modal-header alert-danger">
						<h5 className="modal-title">Editor User Profile</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="form-label-group text-left">
							<label htmlFor="exchangeName">Choose exchange</label>
							<select
								id="exchangeName"
								className="custom-select mr-1"
								onChange={(ev: any) => {
									updateObjUser({ ...objUser, exchange: ev.target.value })
								}}
							>
								{listExchanges}
							</select>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="userNickName">Enter your exchange nickName</label>
							<input
								type="text"
								id="userNickName"
								className="form-control"
								placeholder="Your nickName"
								onChange={(ev: any) => {
									updateObjUser({ ...objUser, [ev.target.id]: ev.target.value })
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="exchangeUserId">Enter your exchange UserId</label>
							<input
								type="text"
								id="exchangeUserId"
								className="form-control"
								placeholder="Your exchangeUserId"
								onChange={(ev: any) => {
									updateObjUser({ ...objUser, [ev.target.id]: ev.target.value })
								}}
							/>
						</div>

						<button
							name="editProfileUser"
							className="btn btn-info btn-block mt-3"
							type="button"
							onClick={(ev: any) => {
								if (objUser.userNickName !== "" && objUser.exchangeUserId !== "") {
									validateForm(objUser, ev.target.name)
									$("#userNickName").val("")
									$("#exchangeUserId").val("")
									updateObjUser({
										...objUser,
										exchange: "",
										exchangeUserId: "",
										userNickName: "",
									})
								}
							}}
						>
							Save Changes
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Сброс пароля юзера
export const PasswordResetModal: React.FC<IPasswordResetModal> = props => {
	return (
		<div
			className="modal fade"
			id="modal-reset"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="exampleModalCenterTitle"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className="modal-header alert-danger">
						<h5 className="modal-title">Reset Password</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="form-label-group text-left">
							<label htmlFor="inputLogin">Enter your email</label>
							<input
								type="text"
								id="inputLogin"
								className="form-control"
								placeholder="your@mail.com"
								required
								autoFocus
								onChange={(ev: any) => {
									const pattern = PATTERN_EMAIL
									isValideField(ev.target.id, pattern)
								}}
							/>
							<div className="invalid-feedback">{CONSTANTS.FEEDBACK_EMAIL}</div>
						</div>

						<button
							name="resetPass"
							onClick={(ev: any) => {
								const inputLogin = $("#inputLogin").val()
								if (inputLogin !== "") {
									const objUser = {
										inputLogin,
									}
									props.validateForm(objUser, ev.target.name)
									$("#inputLogin").val("")
								} else {
									props.handlerPopupWindow(STYLES.WARNING, CONSTANTS.EMAIL_EMPTY)
									startModalAlert()
								}
							}}
							className="btn btn-info btn-block mt-3"
							type="button"
						>
							Reset Password
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Редактирование ордера
export const EditOrderModal: React.FC<IEditOrderModal> = props => {
	const {
		orderDetails,
		dataConstants,
		handlerFilterDetails,
		updateItemDetails,
	} = props

	const { paytypes } = dataConstants

	const startStorage = {
		orderId: "",
		payMethodId: "",
		payMethodName: "",
		payMerchantAccount: "",
		tradeType: "",
	}
	const [orderProps, handlerProps] = React.useState(startStorage)

	React.useEffect(() => {
		if (Object.keys(orderDetails).length !== 0) {
			// console.log(orderDetails)
			handlerProps({
				orderId: orderDetails.orderId,
				payMethodId: orderDetails.payMethodId,
				payMethodName: orderDetails.payMethodName,
				payMerchantAccount: orderDetails.payMerchantAccount,
				tradeType: orderDetails.tradeType,
			})
		}
	}, [orderDetails, handlerProps])

	const listPayMethods = paytypes.map((item: any, index: number) => {
		return (
			<option key={index} value={item.id}>
				{item.payType}
			</option>
		)
	})

	const sortedSubAccounts = getArraySortedByProp(
		"subAccount",
		CONSTANTS.ARRAY_SUB_ACCOUNTS
	)
	const listSubAccounts = sortedSubAccounts.map(
		(item: any, index: number) => {
			return (
				<option key={index} value={item.subAccount} title={item.remarkTooltip}>
					{`${item.subAccount}`}
				</option>
			)
		}
	)
	const classTradeType =
		orderProps.tradeType === "BUY" ? "success" : "danger"
	return (
		<div
			className="modal fade"
			id="modal-editOrder"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modalEditOrder"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className={`modal-header alert-${classTradeType}`}>
						<h5 className="modal-title">
							Edit Order | orderId:{" "}
							{orderProps.orderId !== ""
								? ` ****${orderProps.orderId.slice(-10)}`
								: ""}
						</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="form-label-group text-left mb-2">
							<label htmlFor="tradeType">
								{`tradeType: ${orderProps.tradeType}`}
							</label>
							<select
								name="tradeType"
								className="form-control form-control-sm"
								value={orderProps.tradeType === null ? "" : orderProps.tradeType}
								onChange={(ev: any) => {
									handlerProps({
										...orderProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							>
								<option value="BUY" title="BUY">
									BUY
								</option>
								<option value="SELL" title="SELL">
									SELL
								</option>
							</select>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="payMethodName">
								<span className="icon-pay-dots">
									<img
										src={
											orderProps.payMethodName === ""
												? ""
												: getUrlIcon("iconPaymentByID", orderProps.payMethodId)
										}
										alt="-"
										title={orderProps.payMethodName}
									/>
									{orderProps.payMethodName}
								</span>
							</label>
							<select
								name="payMethodId"
								className="form-control form-control-sm"
								value={
									orderProps.payMethodId === null ? "" : orderProps.payMethodId
								}
								onChange={(ev: any) => {
									handlerProps({
										...orderProps,
										[ev.target.name]: ev.target.value,
										payMethodName: paytypes.filter((item: any) => {
											return item.id === ev.target.value ? item : null
										})[0].payType,
									})
								}}
							>
								{listPayMethods}
							</select>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="payMerchantAccount">
								{`subAccount: 
								${
									orderProps.payMerchantAccount === ""
										? "xxx"
										: orderProps.payMerchantAccount
								}`}
							</label>
							<select
								name="payMerchantAccount"
								className="form-control form-control-sm"
								value={
									orderProps.payMerchantAccount === null
										? ""
										: orderProps.payMerchantAccount
								}
								onChange={(ev: any) => {
									handlerProps({
										...orderProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							>
								<option value="xxx" title="subAccount">
									subAccount
								</option>
								{listSubAccounts}
							</select>
						</div>

						<button
							name="editOrder-btn"
							className="btn btn-info btn-block mt-3"
							type="button"
							onClick={() => {
								$("#modal-editOrder").modal("hide")
								const objItem = {
									itemFlag: "orderItem",
									itemDetails: {
										...orderDetails,
										payMethodId: orderProps.payMethodId,
										payMethodName: orderProps.payMethodName,
										payMerchantAccount: orderProps.payMerchantAccount,
										tradeType: orderProps.tradeType,
									},
								}
								// очищение хранилища itemDetails
								handlerFilterDetails("", "orderDetails", "")
								// console.log(objItem)
								updateItemDetails(objItem)
							}}
						>
							Save Order
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Редактирование p2p-сервиса
export const EditExchangeItemModal: React.FC<IEditExchangeItemModal> = props => {
	const { itemDetails, handlerFilterDetails, updateItemDetails } = props

	const startStorage = {
		id: "",
		name: "",
		shortName: "",
		bg: "",
		logo: "",
		merchantDetail: "",
		advDetail: "",
		orderDetail: "",
		spotTrade: "",
		futTrade: "",
		status: false,
	}
	const [exchangeProps, handlerProps] = React.useState(startStorage)

	React.useEffect(() => {
		if (Object.keys(itemDetails).length !== 0) {
			const startStorage = {
				id: itemDetails.id,
				name: itemDetails.name,
				shortName: itemDetails.shortName,
				bg: itemDetails.bg,
				logo: itemDetails.logo,
				merchantDetail: itemDetails.merchantDetail,
				advDetail: itemDetails.advDetail,
				orderDetail: itemDetails.orderDetail,
				spotTrade: itemDetails.spotTrade,
				futTrade: itemDetails.futTrade,
				status: itemDetails.status === 1 ? true : false,
			}
			handlerProps(startStorage)
		}
	}, [itemDetails, handlerProps])

	return (
		<div
			className="modal fade"
			id="modal-editExchange"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modalEditExchange"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className={`modal-header alert-success`}>
						<h5 className="modal-title">
							Edit {exchangeProps.name} | ExchangeId:
							{exchangeProps.id !== ""
								? ` ****${exchangeProps.id.slice(-10)}`
								: ""}
						</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="form-label-group text-left">
							<label
								htmlFor="nameExchange"
								className="d-flex justify-content-between"
							>
								<span className="icon-pay-dots">
									<img
										src={
											exchangeProps.logo === ""
												? ""
												: `${EXCHANGE_ICON_URL}${exchangeProps.logo}`
										}
										alt="-"
										title={exchangeProps.name}
									/>
									{exchangeProps.name}
								</span>
								<span>
									<Switch
										name="status"
										color="secondary"
										size="small"
										checked={exchangeProps.status}
										onChange={() => {
											handlerProps({
												...exchangeProps,
												status: !exchangeProps.status,
											})
										}}
									/>
									<span
										className={`text-${
											exchangeProps.status ? "success" : "danger"
										} ml-2`}
									>
										{exchangeProps.status ? "status On" : "status Off"}
									</span>
								</span>
							</label>
							<input
								type="text"
								name="name"
								id="nameExchange"
								className="form-control form-control-sm"
								value={exchangeProps.name === null ? "" : exchangeProps.name}
								onChange={(ev: any) => {
									handlerProps({
										...exchangeProps,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="shortName">shortName:</label>
							<input
								type="text"
								id="shortName"
								className="form-control form-control-sm"
								value={
									exchangeProps.shortName === null ? "" : exchangeProps.shortName
								}
								onChange={(ev: any) => {
									handlerProps({ ...exchangeProps, shortName: ev.target.value })
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="bg">logo:</label>
							<input
								type="text"
								id="logo"
								className="form-control form-control-sm"
								value={exchangeProps.logo === null ? "" : exchangeProps.logo}
								onChange={(ev: any) => {
									handlerProps({ ...exchangeProps, logo: ev.target.value })
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="bg">bg:</label>
							<input
								type="text"
								id="bg"
								className="form-control form-control-sm"
								value={exchangeProps.bg === null ? "" : exchangeProps.bg}
								onChange={(ev: any) => {
									handlerProps({ ...exchangeProps, bg: ev.target.value })
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="advDetail">URL advDetail:</label>
							<input
								type="text"
								id="advDetail"
								className="form-control form-control-sm"
								value={
									exchangeProps.advDetail === null ? "" : exchangeProps.advDetail
								}
								onChange={(ev: any) => {
									handlerProps({ ...exchangeProps, advDetail: ev.target.value })
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="merchantDetail">URL merchantDetail:</label>
							<input
								type="text"
								id="merchantDetail"
								className="form-control form-control-sm"
								value={
									exchangeProps.merchantDetail === null
										? ""
										: exchangeProps.merchantDetail
								}
								onChange={(ev: any) => {
									handlerProps({
										...exchangeProps,
										merchantDetail: ev.target.value,
									})
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="orderDetail">URL orderDetail:</label>
							<input
								type="text"
								id="orderDetail"
								className="form-control form-control-sm"
								value={
									exchangeProps.orderDetail === null
										? ""
										: exchangeProps.orderDetail
								}
								onChange={(ev: any) => {
									handlerProps({ ...exchangeProps, orderDetail: ev.target.value })
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="spotTrade">URL spotTrade:</label>
							<input
								type="text"
								id="spotTrade"
								className="form-control form-control-sm"
								value={
									exchangeProps.spotTrade === null ? "" : exchangeProps.spotTrade
								}
								onChange={(ev: any) => {
									handlerProps({ ...exchangeProps, spotTrade: ev.target.value })
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="futTrade">URL futTrade:</label>
							<input
								type="text"
								id="futTrade"
								className="form-control form-control-sm"
								value={
									exchangeProps.futTrade === null ? "" : exchangeProps.futTrade
								}
								onChange={(ev: any) => {
									handlerProps({ ...exchangeProps, futTrade: ev.target.value })
								}}
							/>
						</div>

						<button
							type="button"
							className="btn btn-info btn-block mt-3"
							name="editExchange-btn"
							onClick={() => {
								$("#modal-editExchange").modal("hide")
								const objItem = {
									itemFlag: "exchangeItem",
									itemDetails: {
										...exchangeProps,
										status: exchangeProps.status === true ? 1 : 0,
									},
								}
								// очищение хранилища itemDetails
								handlerFilterDetails("", "itemDetails", "")
								// console.log(objItem)
								updateItemDetails(objItem)
							}}
						>
							Save Exchange
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Редактирование вида крипты / фиата
export const EditCurrencyItemModal: React.FC<IEditCurrencyItemModal> = props => {
	const {
		dataConstants,
		itemDetails,
		handlerFilterDetails,
		updateItemDetails,
	} = props

	const { exchanges } = dataConstants

	const listOptionsExchanges = exchanges.map((item: any, index: number) => {
		const elem = item.status ? (
			<option key={index} value={item.id}>
				{item.name}
			</option>
		) : null
		return elem
	})

	const startStorage = {
		id: "",
		currency: "",
		currencyName: "", // bitcoin, etherium
		currencyType: "", // ['coin', 'fiat']
		symbol: "", // "₽", "$"
		iconUrl: "", // `RUB.png`
		tickerUSDT: "", // `ETHUSDT.png`
		currencyProps: [],
		// === additionalFields ===
		isOpenCurrencyProps: false,
		currencyPropsExchangeId: "",
		currencyPropsCoinId: "",
		currencyPropsCoinName: "",
	}
	const [currencyDetails, handlerProps] = React.useState(startStorage)

	React.useEffect(() => {
		if (Object.keys(itemDetails).length !== 0) {
			const startStorage = {
				id: itemDetails.id,
				currency: itemDetails.currency,
				currencyName: itemDetails.currencyName,
				currencyType: itemDetails.currencyType,
				symbol: itemDetails.symbol,
				iconUrl: itemDetails.iconUrl,
				tickerUSDT: itemDetails.tickerUSDT,
				currencyProps: itemDetails.currencyProps,
				// === additionalFields ===
				isOpenCurrencyProps: false,
				currencyPropsExchangeId: "",
				currencyPropsCoinId: "",
				currencyPropsCoinName: "",
			}
			handlerProps(startStorage)
		}
	}, [itemDetails, handlerProps])

	// получение полей input currencyPropsCoinId | currencyPropsCoinName
	const getInputDefaultValue = (flagInput: string, exchangeId: string) => {
		const arrProps: any = currencyDetails.currencyProps.slice()
		let value = ""
		for (let i = 0; i < arrProps.length; i++) {
			if (arrProps[i].exchangeId === exchangeId) {
				value =
					flagInput === "coinId" ? arrProps[i].coinId : arrProps[i].coinName
			}
		}
		// console.log(value)
		return value
	}

	// получение обновленного CurrencyProps
	const getCurrencyPropsUpdated = (
		flagInput: string,
		value: string,
		exchangeId: string
	) => {
		const arrProps: any = currencyDetails.currencyProps.slice()
		// Если currencyDetails.currencyProps не пустой
		if (arrProps.length !== 0) {
			for (let i = 0; i < arrProps.length; i++) {
				// если item с таким exchangeId существует
				if (arrProps[i].exchangeId === exchangeId) {
					flagInput === "coinId"
						? (arrProps[i].coinId = value)
						: (arrProps[i].coinName = value)
				}
				// если item с таким exchangeId НЕ существует
				else {
					//  - добавляем на последней итерации
					if (i === arrProps.length - 1)
						arrProps.push({
							coinId: value,
							// coinId: "",
							coinName: value,
							// coinName: "",
							exchangeId,
							switchedOn: false,
						})
				}
			}
		}
		// Если currencyDetails.currencyProps пустой
		// создаем первый элемент currencyProps
		else {
			arrProps.push({
				payId: value,
				payName: value,
				exchangeId,
				switchedOn: false,
			})
		}
		return arrProps
	}

	return (
		<div
			className="modal fade"
			id="modal-editCurrency"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modalEditCurrency"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className={`modal-header alert-success`}>
						<h5 className="modal-title">
							Edit {currencyDetails.currency} | CurrencyId:
							{currencyDetails.id !== ""
								? ` ****${currencyDetails.id.slice(-10)}`
								: ""}
						</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						{/* currency */}
						<div className="form-label-group text-left">
							<label htmlFor="Currency">
								<span className="icon-pay-dots">
									<img
										src={
											currencyDetails.iconUrl === ""
												? ""
												: `${CURRENCY_ICON_URL}${currencyDetails.iconUrl}`
										}
										alt="-"
										title={currencyDetails.currency}
									/>
									{currencyDetails.currency}
								</span>
							</label>
							<input
								type="text"
								id="currency"
								name="currency"
								className="form-control form-control-sm"
								value={
									currencyDetails.currency === null ? "" : currencyDetails.currency
								}
								onChange={(ev: any) => {
									handlerProps({
										...currencyDetails,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>
						{/* currencyName */}
						<div className="form-label-group text-left">
							<label htmlFor="currencyName">CurrencyName</label>
							<input
								type="text"
								id="currencyName"
								name="currencyName"
								className="form-control form-control-sm"
								value={
									currencyDetails.currencyName === null
										? ""
										: currencyDetails.currencyName
								}
								onChange={(ev: any) => {
									handlerProps({
										...currencyDetails,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>
						{/* symbol */}
						<div className="form-label-group text-left">
							<label htmlFor="symbol">CurrencySymbol</label>
							<input
								type="text"
								id="symbol"
								name="symbol"
								className="form-control form-control-sm"
								value={
									currencyDetails.symbol === null ? "" : currencyDetails.symbol
								}
								onChange={(ev: any) => {
									handlerProps({
										...currencyDetails,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>
						{/* iconUrl */}
						<div className="form-label-group text-left">
							<label htmlFor="iconCurrency">CurrencyIconUrl</label>
							<input
								type="text"
								id="iconCurrency"
								name="iconUrl"
								className="form-control form-control-sm"
								value={
									currencyDetails.iconUrl === null ? "" : currencyDetails.iconUrl
								}
								onChange={(ev: any) => {
									handlerProps({
										...currencyDetails,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>
						{/* tickerUSDT */}
						<div className="form-label-group text-left">
							<label htmlFor="tickerUSDT">CurrencytickerUSDT</label>
							<input
								type="text"
								id="tickerUSDT"
								name="tickerUSDT"
								className="form-control form-control-sm"
								value={
									currencyDetails.tickerUSDT === null
										? ""
										: currencyDetails.tickerUSDT
								}
								onChange={(ev: any) => {
									handlerProps({
										...currencyDetails,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>
						{/* currencyType select */}
						<div className="form-label-group text-left">
							<label htmlFor="currencyType">CurrencyType</label>
							<select
								id="currencyType"
								name="currencyType"
								className="form-control form-control-sm"
								value={
									currencyDetails.currencyType === null
										? ""
										: currencyDetails.currencyType
								}
								onChange={(ev: any) => {
									handlerProps({
										...currencyDetails,
										[ev.target.name]: ev.target.value,
									})
								}}
							>
								<option value="">Choose Type Currency</option>
								<option value="coin">Coin</option>
								<option value="fiat">Fiat</option>
							</select>
						</div>
						{/* CurrencyProps */}
						{/* <div className="form-label-group text-left mt-2">
							<div className="d-flex justify-content-between">
								<span>CurrencyProps</span>
								<span>
									<Switch
										name="status"
										color="secondary"
										size="small"
										checked={currencyDetails.isOpenCurrencyProps}
										onChange={() => {
											handlerProps({
												...currencyDetails,
												isOpenCurrencyProps: !currencyDetails.isOpenCurrencyProps,
											})
										}}
									/>
									<span
										className={`text-${
											currencyDetails.isOpenCurrencyProps ? "success" : "danger"
										} ml-2`}
									>
										{currencyDetails.isOpenCurrencyProps ? "On" : "Off"}
									</span>
								</span>
							</div>
						</div> */}
						{/* currencyPropsExchangeId */}
						<div className="form-label-group text-left mt-2">
							<label htmlFor="currencyType">currencyProps</label>
							<select
								id="currencyPropsExchangeId"
								name="currencyPropsExchangeId"
								className="form-control form-control-sm"
								value={
									currencyDetails.currencyPropsExchangeId === null
										? ""
										: currencyDetails.currencyPropsExchangeId
								}
								onChange={(ev: any) => {
									handlerProps({
										...currencyDetails,
										currencyPropsExchangeId: ev.target.value,
										currencyPropsCoinId: getInputDefaultValue(
											"coinId",
											ev.target.value
										),
										currencyPropsCoinName: getInputDefaultValue(
											"coinName",
											ev.target.value
										),
									})
								}}
							>
								<option value="">Choose Exchange</option>
								{listOptionsExchanges}
							</select>
						</div>

						{currencyDetails.currencyPropsExchangeId !== "" ? (
							<>
								{/* currencyPropsCoinId */}
								<div className="form-label-group text-left">
									<label htmlFor="coinId">coinId</label>
									<input
										type="text"
										id="currencyPropsCoinId"
										name="currencyPropsCoinId"
										className="form-control form-control-sm"
										value={
											currencyDetails.currencyPropsCoinId === null
												? ""
												: currencyDetails.currencyPropsCoinId
										}
										onChange={(ev: any) => {
											handlerProps({
												...currencyDetails,
												[ev.target.name]: ev.target.value,
												currencyProps: getCurrencyPropsUpdated(
													"coinId",
													ev.target.value,
													currencyDetails.currencyPropsExchangeId
												),
											})
										}}
									/>
								</div>
								{/* currencyPropsCoinName */}
								<div className="form-label-group text-left">
									<label htmlFor="coinName">coinName</label>
									<input
										type="text"
										id="currencyPropsCoinName"
										name="currencyPropsCoinName"
										className="form-control form-control-sm"
										value={
											currencyDetails.currencyPropsCoinName === null
												? ""
												: currencyDetails.currencyPropsCoinName
										}
										onChange={(ev: any) => {
											handlerProps({
												...currencyDetails,
												[ev.target.name]: ev.target.value,
												currencyProps: getCurrencyPropsUpdated(
													"coinName",
													ev.target.value,
													currencyDetails.currencyPropsExchangeId
												),
											})
										}}
									/>
								</div>
							</>
						) : null}

						<button
							name="editCurrency-btn"
							onClick={() => {
								$("#modal-editCurrency").modal("hide")
								const objItem = {
									itemFlag: "currencyItem",
									itemDetails: {
										currencyId: currencyDetails.id,
										currency: currencyDetails.currency,
										currencyName: currencyDetails.currencyName,
										currencyType: currencyDetails.currencyType,
										symbol: currencyDetails.symbol,
										iconUrl: currencyDetails.iconUrl,
										tickerUSDT: currencyDetails.tickerUSDT,
										currencyProps: currencyDetails.currencyProps,
									},
								}
								// сброс стейта к дефолту
								handlerProps({
									id: "",
									currency: "",
									currencyName: "",
									currencyType: "",
									symbol: "",
									iconUrl: "",
									tickerUSDT: "",
									currencyProps: [],
									// === additionalFields ===
									isOpenCurrencyProps: false,
									currencyPropsExchangeId: "",
									currencyPropsCoinId: "",
									currencyPropsCoinName: "",
								})
								// очищение хранилища itemDetails
								handlerFilterDetails("", "itemDetails", "")
								// console.log(objItem)
								updateItemDetails(objItem)
							}}
							className="btn btn-info btn-block mt-3"
							type="button"
						>
							Save Currency
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Редактирование метода платежа
export const EditPaymentItemModal: React.FC<IEditPaymentItemModal> = props => {
	const {
		dataConstants,
		itemDetails,
		handlerFilterDetails,
		updateItemDetails,
	} = props

	const { exchanges } = dataConstants

	const listOptionsExchanges = exchanges.map((item: any, index: number) => {
		const elem = item.status ? (
			<option key={index} value={item.id}>
				{item.name}
			</option>
		) : null
		return elem
	})

	const startStorage = {
		id: "",
		payType: "",
		iconUrlColor: "",
		paymentProps: [],
		// === additionalFields ===
		paymentPropsExchangeId: "",
		paymentPropsPayId: "",
		paymentPropsPayName: "",
	}
	const [paymentDetails, handlerProps] = React.useState(startStorage)

	React.useEffect(() => {
		if (Object.keys(itemDetails).length !== 0) {
			handlerProps({
				id: itemDetails.id,
				payType: itemDetails.payType,
				iconUrlColor: itemDetails.iconUrlColor,
				paymentProps: itemDetails.payTypeProps,
				// === additionalFields ===
				paymentPropsExchangeId: "",
				paymentPropsPayId: "",
				paymentPropsPayName: "",
			})
		}
	}, [itemDetails, handlerProps])

	// получение полей input paymentPropsPayId | paymentPropsPayName
	const getInputDefaultValue = (flagInput: string, exchangeId: string) => {
		const arrProps: any = paymentDetails.paymentProps.slice()
		let value = ""
		for (let i = 0; i < arrProps.length; i++) {
			if (arrProps[i].exchangeId === exchangeId) {
				value = flagInput === "payId" ? arrProps[i].payId : arrProps[i].payName
			}
		}
		// console.log(value)
		return value
	}

	// получение обновленного CurrencyProps
	const getPaymentPropsUpdated = (
		flagInput: string,
		value: string,
		exchangeId: string
	) => {
		const arrProps: any = paymentDetails.paymentProps.slice()
		// Если paymentDetails.paymentProps не пустой
		if (arrProps.length !== 0) {
			for (let i = 0; i < arrProps.length; i++) {
				// если item с таким exchangeId существует
				if (arrProps[i].exchangeId === exchangeId) {
					flagInput === "payId"
						? (arrProps[i].payId = value)
						: (arrProps[i].payName = value)
				}
				// если item с таким exchangeId НЕ существует
				else {
					//  - добавляем на последней итерации
					if (i === arrProps.length - 1) {
						arrProps.push({
							payId: value,
							payName: value,
							exchangeId,
							switchedOn: false,
						})
					}
				}
			}
		}
		// Если paymentDetails.paymentProps пустой
		// создаем первый элемент paymentProps
		else {
			arrProps.push({
				payId: value,
				payName: value,
				exchangeId,
				switchedOn: false,
			})
		}
		return arrProps
	}

	return (
		<div
			className="modal fade"
			id="modal-editPayType"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modal-editPayType"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className={`modal-header alert-success`}>
						<h5 className="modal-title">
							Edit {paymentDetails.payType} | payTypeId:
							{paymentDetails.id !== ""
								? ` ****${paymentDetails.id.slice(-10)}`
								: ""}
						</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						{/* payType */}
						<div className="form-label-group text-left">
							<label htmlFor="payType">
								<span className="icon-pay-dots">
									<img
										src={
											paymentDetails.iconUrlColor === ""
												? ""
												: `${PAY_ICON_URL}${paymentDetails.iconUrlColor}`
										}
										title={paymentDetails.payType}
										alt="-"
									/>
									{paymentDetails.payType}
								</span>
							</label>
							<input
								type="text"
								id="payType"
								name="payType"
								className="form-control form-control-sm"
								value={
									paymentDetails.payType === null ? "" : paymentDetails.payType
								}
								onChange={(ev: any) => {
									handlerProps({
										...paymentDetails,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>
						{/* iconUrlColor */}
						<div className="form-label-group text-left">
							<label htmlFor="iconPayType">iconUrlColor</label>
							<input
								type="text"
								id="iconPayType"
								name="iconUrlColor"
								className="form-control form-control-sm"
								value={
									paymentDetails.iconUrlColor === null
										? ""
										: paymentDetails.iconUrlColor
								}
								onChange={(ev: any) => {
									handlerProps({
										...paymentDetails,
										[ev.target.name]: ev.target.value,
									})
								}}
							/>
						</div>
						{/* paymentPropsExchangeId */}
						<div className="form-label-group text-left mt-2">
							<label htmlFor="paymentPropsExchangeId">paymentProps</label>
							<select
								id="paymentPropsExchangeId"
								name="paymentPropsExchangeId"
								className="form-control form-control-sm"
								value={
									paymentDetails.paymentPropsExchangeId === null
										? ""
										: paymentDetails.paymentPropsExchangeId
								}
								onChange={(ev: any) => {
									handlerProps({
										...paymentDetails,
										paymentPropsExchangeId: ev.target.value,
										paymentPropsPayId: getInputDefaultValue(
											"payId",
											ev.target.value
										),
										paymentPropsPayName: getInputDefaultValue(
											"payName",
											ev.target.value
										),
									})
								}}
							>
								<option value="">Choose Exchange</option>
								{listOptionsExchanges}
							</select>
						</div>

						{paymentDetails.paymentPropsExchangeId !== "" ? (
							<>
								{/* paymentPropsPayId */}
								<div className="form-label-group text-left">
									<label htmlFor="paymentPropsPayId">PayId</label>
									<input
										type="text"
										id="paymentPropsPayId"
										name="paymentPropsPayId"
										className="form-control form-control-sm"
										value={
											paymentDetails.paymentPropsPayId === null
												? ""
												: paymentDetails.paymentPropsPayId
										}
										onChange={(ev: any) => {
											handlerProps({
												...paymentDetails,
												paymentPropsPayId: ev.target.value,
												paymentProps: getPaymentPropsUpdated(
													"payId",
													ev.target.value,
													paymentDetails.paymentPropsExchangeId
												),
											})
										}}
									/>
								</div>
								{/* paymentPropsPayName */}
								<div className="form-label-group text-left">
									<label htmlFor="paymentPropsPayName">payName</label>
									<input
										type="text"
										id="paymentPropsPayName"
										name="paymentPropsPayName"
										className="form-control form-control-sm"
										value={
											paymentDetails.paymentPropsPayName === null
												? ""
												: paymentDetails.paymentPropsPayName
										}
										onChange={(ev: any) => {
											handlerProps({
												...paymentDetails,
												paymentPropsPayName: ev.target.value,
												paymentProps: getPaymentPropsUpdated(
													"payName",
													ev.target.value,
													paymentDetails.paymentPropsExchangeId
												),
											})
										}}
									/>
								</div>
							</>
						) : null}

						<button
							name="editCurrency-btn"
							onClick={() => {
								$("#modal-editPayType").modal("hide")
								const objItem = {
									itemFlag: "paymentItem",
									itemDetails: {
										payTypeId: paymentDetails.id,
										payType: paymentDetails.payType,
										iconUrlColor: paymentDetails.iconUrlColor,
										payTypeProps: paymentDetails.paymentProps,
									},
								}
								// сброс стейта к дефолту
								handlerProps({
									id: "",
									payType: "",
									iconUrlColor: "",
									paymentProps: [],
									// === additionalFields ===
									paymentPropsExchangeId: "",
									paymentPropsPayId: "",
									paymentPropsPayName: "",
								})
								// очищение хранилища itemDetails
								handlerFilterDetails("", "itemDetails", "")
								// console.log(objItem)
								updateItemDetails(objItem)
							}}
							className="btn btn-info btn-block mt-3"
							type="button"
						>
							Save PayType
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Редактирование OrderStatus
export const EditOrderStatusModal: React.FC<IEditOrderStatusModal> = props => {
	const {
		dataConstants,
		itemDetails,
		handlerFilterDetails,
		updateItemDetails,
	} = props

	const { exchanges } = dataConstants

	const startStorage = {
		id: "",
		colorStatus: "",
		status: "",
		values: [],
		filteredValues: [],
		additionalStatus: "",
		statusValuesExchangeId: "",
	}
	const [statusProps, handlerStatusProps] = React.useState(startStorage)

	React.useEffect(() => {
		if (Object.keys(itemDetails).length !== 0) {
			const startObj = {
				id: itemDetails.id,
				colorStatus: itemDetails.colorStatus,
				status: itemDetails.status,
				values: itemDetails.values,
				filteredValues: [],
				additionalStatus: "",
				statusValuesExchangeId: "",
			}
			handlerStatusProps(startObj)
		}
	}, [itemDetails, handlerStatusProps])

	const getStatusValuesUpdated = (valueId: string, statusValue: string) => {
		const arr: any = statusProps.values.slice()
		for (let i = 0; i < arr.length; i++) {
			if (arr[i]._id === valueId) arr[i].value = statusValue
		}
		return arr
	}

	const listOptionsExchanges = exchanges.map((item: any, index: number) => {
		const elem = item.status ? (
			<option key={index} value={item.id}>
				{item.name}
			</option>
		) : null
		return elem
	})

	return (
		<div
			className="modal fade"
			id="modal-editOrderStatus"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modalEditOrderStatus"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className={`modal-header alert-success`}>
						<h5 className="modal-title">Edit {statusProps.status} Status</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="form-label-group text-left">
							<label htmlFor="shortName">status:</label>
							<input
								type="text"
								id="status"
								className="form-control form-control-sm"
								value={statusProps.status === null ? "" : statusProps.status}
								onChange={(ev: any) => {
									handlerStatusProps({ ...statusProps, status: ev.target.value })
								}}
							/>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="bg">colorStatus:</label>
							<input
								type="text"
								id="colorStatus"
								className="form-control form-control-sm"
								value={
									statusProps.colorStatus === null ? "" : statusProps.colorStatus
								}
								onChange={(ev: any) => {
									handlerStatusProps({
										...statusProps,
										colorStatus: ev.target.value,
									})
								}}
							/>
						</div>

						{/* statusValuesExchangeId */}
						<div className="form-label-group text-left mt-2">
							<label htmlFor="statusValuesExchangeId">Exchange</label>
							<select
								id="statusValuesExchangeId"
								name="statusValuesExchangeId"
								className="form-control form-control-sm"
								value={
									statusProps.statusValuesExchangeId === null
										? ""
										: statusProps.statusValuesExchangeId
								}
								onChange={(ev: any) => {
									const filteredStatus: any = statusProps.values.filter(
										(item: any) => {
											return item.exchangeId === ev.target.value
										}
									)
									handlerStatusProps({
										...statusProps,
										statusValuesExchangeId: ev.target.value,
										filteredValues: filteredStatus,
									})
								}}
							>
								<option value="">Choose Exchange</option>
								{listOptionsExchanges}
							</select>
						</div>

						{statusProps.statusValuesExchangeId !== "" ? (
							<>
								{statusProps.filteredValues.map((item: any, index: any) => {
									return (
										<div key={index} className="form-label-group text-left">
											<label htmlFor={`statusValue_${index}`}>{`statusValue_${index +
												1}`}</label>
											<input
												type="text"
												id={`statusValue_${index}`}
												name="statusValue"
												className="form-control form-control-sm"
												value={item.value === null ? "" : item.value}
												onChange={(ev: any) => {
													handlerStatusProps({
														...statusProps,
														values: getStatusValuesUpdated(item._id, ev.target.value),
													})
												}}
											/>
										</div>
									)
								})}

								<div className="form-label-group text-left">
									<label htmlFor="additionalStatus">additionalStatusValue</label>
									<input
										type="text"
										id="additionalStatus"
										name="additionalStatus"
										className="form-control form-control-sm"
										value={
											statusProps.additionalStatus === null
												? ""
												: statusProps.additionalStatus
										}
										onChange={(ev: any) => {
											handlerStatusProps({
												...statusProps,
												additionalStatus: ev.target.value,
											})
										}}
									/>
								</div>
							</>
						) : null}

						<button
							type="button"
							className="btn btn-info btn-block mt-3"
							name="editOrderStatus-btn"
							onClick={() => {
								$("#modal-editOrderStatus").modal("hide")
								const objItem = {
									itemFlag: "statusItem",
									itemDetails: {
										idStatus: statusProps.id,
										colorStatus: statusProps.colorStatus,
										nameStatus: statusProps.status,
										values: statusProps.values,
										additionalStatus: {
											exchangeId: statusProps.statusValuesExchangeId,
											value: statusProps.additionalStatus,
										},
									},
								}
								// очищение хранилища itemDetails
								handlerFilterDetails("", "itemDetails", "")
								// console.log(objItem)
								updateItemDetails(objItem)
							}}
						>
							Save orderStatus
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Редактирование списка оплат юзера
export const EditUserPayTypesModal: React.FC<IEditUserPayTypesModal> = props => {
	const { userProfile, dataConstants, getListOption, updateUser } = props
	const { exchanges, paytypes } = dataConstants

	const [objDetails, updateObjUser] = React.useState({
		exchange: "",
		payType: "",
		payList: [""],
	})

	const listExchanges = getListOption(exchanges, "listExchanges")
	const listPayTypes = getListOption(paytypes, "payTypeList")
	return (
		<div
			className="modal fade"
			id="modal-editPayTypesUser"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modalEditPayment"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className="modal-header alert-success">
						<h5 className="modal-title">Editor User Profile</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="form-label-group text-left">
							<label htmlFor="exchangeName">
								{`Choose exchange | ${objDetails.exchange}`}
							</label>
							<select
								id="exchangeName"
								className="custom-select mr-1"
								onChange={(ev: any) => {
									updateObjUser({
										...objDetails,
										exchange: ev.target.value,
									})
								}}
							>
								<option value="all">Choose exchange</option>
								{listExchanges}
							</select>
						</div>

						<div className="form-label-group text-left">
							<label htmlFor="listPayTypes">
								<span
									className="text-danger mr-1"
									style={{ cursor: "pointer" }}
									onClick={() => {
										updateObjUser({
											...objDetails,
											payType: "",
											payList: objDetails.payType.split(","),
										})
									}}
								>
									<FontAwesomeIcon icon={faMinusCircle} />
								</span>
								<span>{`Choose PayType | ${objDetails.payType}`}</span>
							</label>
							<select
								id="listPayTypes"
								className="custom-select mr-1"
								onChange={(ev: any) => {
									updateObjUser({
										...objDetails,
										payType:
											objDetails.payType === ""
												? ev.target.value
												: objDetails.payType + "," + ev.target.value,
									})
								}}
							>
								<option value="all">Choose PayType</option>
								{listPayTypes}
							</select>
						</div>

						<button
							name="editPayTypesUser"
							className="btn btn-info btn-block mt-3"
							disabled={
								objDetails.payType === "" ||
								objDetails.exchange === "" ||
								objDetails.payType === "all" ||
								objDetails.exchange === "all"
							}
							type="button"
							onClick={() => {
								if (objDetails.payType !== "") {
									$("#modal-editPayTypesUser").modal("hide")
									const objUser = {
										id: userProfile.id,
										fieldChangeable: "updateUserPayTypes",
										exchange: objDetails.exchange,
										payTypeList: objDetails.payType.split(","),
									}
									// console.log(objUser)
									updateUser(objUser)
									// сброс формы
									updateObjUser({
										exchange: "",
										payType: "",
										payList: [""],
									})
								}
							}}
						>
							Save Changes
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Сохранение балансов в БД
export const BalanceInsertModal: React.FC<IInsertBalanceModal> = props => {
	const {
		balanceDetails,
		currentCourses,
		admin,
		userId,
		insertBalanceToDB,
	} = props

	const obj: any = {
		cashBalanceRUB: 0,
		cashBalanceUSDT: 0,
		creditBalanceRUB: 0,
		creditBalanceUSDT: 0,
		creditAcceptedRUB: 0,
		creditReturnedRUB: 0,
	}
	const trezor = CONSTANTS.ASSETS_ON_WALLETS

	const [details, handlerDetails] = React.useState(obj)

	const fullCourses =
		Array.isArray(currentCourses) && currentCourses.length !== 0
			? true
			: false
	let totalBalance = 0
	let newArr: any[] = []
	const currentAssets = balanceDetails.balances
		? balanceDetails.balances.slice()
		: []
	if (fullCourses && admin) {
		const trezorAssets = trezor.map((item: any) => {
			return {
				summ: +getValuationUSDT(currentCourses, item.asset, +item.volume),
				asset: item.asset,
				exchange: "TZ",
				exchangeId: "63039ac2956b2f07f0e56f21",
				volume: item.volume,
			}
		})
		newArr = trezorAssets
	}
	const currentBalances = currentAssets.concat(newArr)
	const summTrezor =
		currentBalances && currentBalances !== 0
			? getSummUSDT(currentBalances, "TZ")
			: 0
	const listItems =
		currentBalances && currentBalances.length !== 0
			? currentBalances.map((item: any, index: number) => {
					totalBalance += item.summ ? Number(item.summ) : 0.0
					return (
						<span
							key={index}
							className="col-4"
							style={{ fontSize: "0.9em" }}
						>{`${item.exchange}_${item.asset}: $${
							item.summ ? Number(item.summ).toFixed(2) : 0.0
						}`}</span>
					)
			  })
			: null
	return (
		<div
			className="modal fade"
			id="modal-insertBalance"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="modalInsertBalance"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className="modal-header alert-danger">
						<h5 className="modal-title">
							Save Balance | Date: {getLocalDate()}
						</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="tab-content" id="balanceTabContent">
							<div className="row">{listItems}</div>
							<div className="form-label-group text-left">
								<label htmlFor="cash-Balance">
									{!fullCourses ? (
										<span className="text-danger">Download Courses!</span>
									) : null}
								</label>
								<div>
									{`Exchanges Balances: $${(+totalBalance - +summTrezor).toFixed(
										2
									)}`}
								</div>
								{admin ? <div>{`Trezor Balances: $${+summTrezor}`}</div> : null}
								<div>{`CashBalance: $${details.cashBalanceUSDT}`}</div>
								<div>{`CreditBalance: $${details.creditBalanceUSDT}`}</div>
								<div>
									{`Total balance: $${(
										+totalBalance +
										+details.cashBalanceUSDT +
										+details.creditBalanceUSDT
									).toFixed(2)}`}
								</div>
								<input
									type="number"
									id="cash-Balance"
									placeholder="Enter Cash Balance, RUB"
									className="form-control"
									value={details.cashBalanceRUB === 0 ? "" : details.cashBalanceRUB}
									onChange={(ev: any) => {
										handlerDetails({
											...details,
											cashBalanceRUB: ev.target.value,
											cashBalanceUSDT: fullCourses
												? getValuationUSDT(currentCourses, "RUB", +ev.target.value)
												: 0,
										})
									}}
								/>
							</div>
							{admin ? (
								<div className="form-label-group text-left">
									<label htmlFor="credit-Balance">credit-Balance</label>
									<input
										type="number"
										id="credit-Balance"
										placeholder="Enter Credit Balance, RUB"
										className="form-control"
										value={
											details.creditBalanceRUB === 0 ? "" : details.creditBalanceRUB
										}
										onChange={(ev: any) => {
											handlerDetails({
												...details,
												creditBalanceRUB: ev.target.value,
												creditBalanceUSDT: fullCourses
													? getValuationUSDT(currentCourses, "RUB", +ev.target.value)
													: 0,
											})
										}}
									/>
								</div>
							) : null}
						</div>
						<button
							name="saveBalance-btn"
							className="btn btn-info btn-block mt-3"
							type="button"
							disabled={
								details.cashBalanceUSDT === 0 && totalBalance === 0 ? true : false
							}
							onClick={() => {
								$("#modal-insertBalance").modal("hide")
								const objBalanceDB = {
									userId,
									localDate: getLocalDate(),
									balances: currentBalances,
									cashBalanceRUB: details.cashBalanceRUB,
									creditBalanceRUB: details.creditBalanceRUB,
									creditAcceptedRUB: details.creditAcceptedRUB.toString(),
									creditReturnedRUB: details.creditReturnedRUB.toString(),
								}
								// console.log(objBalanceDB)
								insertBalanceToDB(objBalanceDB)
								// сброс значений стейта
								handlerDetails({
									...details,
									cashBalanceRUB: 0,
									cashBalanceUSDT: 0,
									creditBalanceRUB: 0,
									creditBalanceUSDT: 0,
									creditAcceptedRUB: 0,
									creditReturnedRUB: 0,
								})
							}}
						>
							Save Balance
						</button>
					</div>
				</div>
			</div>
		</div>
	)
}

// Редактировние объявления _BN
export const EditAdvModalBN: React.FC<IEditAdvModal> = props => {
	const {
		userId,
		objExchange,
		filterDetails,
		currentCourses,
		p2pBalance,
		merchantPayMethods,
		updateAdv,
		handlerPopupWindow,
		handlerAdvDetails,
		// handlerFilterDetails,
	} = props

	const { advDetails, properties } = filterDetails
	const { id, name, shortName } = objExchange

	const [visible, setVisible] = React.useState(true)

	const calculatedPrice =
		(advDetails.basePrice / 100) * advDetails.priceFloatingRatio

	// подсветка BUY и SELL ордеров
	let classTradeType
	advDetails.tradeType === "BUY"
		? (classTradeType = "success")
		: (classTradeType = "danger")

	// получение суммированного значения input`a
	const calculateValueInput = (elem: any, step: number) => {
		const valueInput: any = $(`#${elem}`).val()
		const summedValue: any = +valueInput + step
		handlerAdvDetails(elem, summedValue)
	}

	let payMethods = null
	const methods = advDetails.tradeMethods
	if (methods) {
		payMethods = merchantPayMethods.map((item: any, index: number) => {
			return (
				<option key={index} value={item.id}>
					{`${item.identifier} id: ${item.id}`}
				</option>
			)
		})
	}

	const listPayTypeIcons =
		methods && methods.length !== 0 ? (
			methods.map((item: any, index: number) => {
				return (
					<span key={index} className="icon-pay-dots-filter">
						<img
							src={getUrlIcon("Payment", item.payType)}
							alt="*"
							title={item.payType}
							id={item.payType}
							onClick={(ev: any) => {
								handlerAdvDetails("payTypeRemove", ev.target.id)
							}}
						/>
					</span>
				)
			})
		) : (
			<span className="text-danger">No payTypes</span>
		)

	let total: any = 0
	let current: any = null
	// let initAmount: any = null
	let free: any = null

	// суммарный объём Asset на p2p-Балансе
	const getP2PAssetTotalBalance = (asset: string, arr: any) => {
		let assetBalance
		let digits = 2
		let deviation = 0.01
		for (let i = 0; i < arr.length; i++) {
			if (arr[i].asset === asset) {
				if (asset === "BTC" || asset === "ETH" || asset === "BNB") {
					digits = 5
					deviation = 0.00001
				}
				const freeze = +parseFloat(arr[i].freeze).toFixed(digits)
				const freeBalance = +parseFloat(arr[i].free).toFixed(digits)
				assetBalance = freeze + freeBalance - deviation
			}
		}
		return assetBalance
	}

	if (p2pBalance.length !== 0) {
		// суммарный объём Asset на p2p-Балансе
		total = getP2PAssetTotalBalance(advDetails.asset, p2pBalance)
		// текущий объём в ордере
		current = +parseFloat(advDetails.surplusAmount).toFixed(2)
		// суммарный объём сделок по объявлению
		// initAmount = +parseFloat(advDetails.initAmount).toFixed(2)
		// свободный объём USDT в ордере
		free = (total - current).toFixed(2)
	}

	const valuationUSDT = getValuationUSDT(
		currentCourses,
		advDetails.asset,
		advDetails.surplusAmount
	)

	return (
		<div
			className="modal fade"
			id="modal-editAdv_BN"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="exampleModalCenterTitle"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className={`modal-header alert-${classTradeType}`}>
						<h5 className="modal-title">{`BN | Edit advNo: ${advDetails.advNo}`}</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="row mb-3">
							{advDetails.priceFloatingRatio === null ? (
								<div className="col-3">
									<div>priceType:</div>
									<div>Fixed</div>
								</div>
							) : (
								<div className="col-3">
									<div>priceType:</div>
									<div className="text-info">Floating</div>
								</div>
							)}
							<div className="col-6">
								<div>tradeType|Asset|Currency</div>
								<div className={`bg-${classTradeType} p-1`}>
									{advDetails.tradeType}
									<span className="icon-pay-dots p-1">
										<img
											src={getUrlIcon("Asset", advDetails.fiatUnit)}
											className="ml-1"
											alt="-"
											title={advDetails.fiatUnit}
										/>
										{advDetails.fiatUnit}
									</span>
									<span className="icon-pay-dots p-1">
										<img
											src={getUrlIcon("Asset", advDetails.asset)}
											className="ml-1"
											alt="-"
											title={advDetails.asset}
										/>
										{advDetails.asset}
									</span>
								</div>
							</div>

							<div className="col-3">
								<div>Status:</div>
								<div>
									{advDetails.advStatus === 1 ? (
										<span className="text-success">Published</span>
									) : (
										<span className="text-warning">Offline</span>
									)}
								</div>
							</div>
						</div>
						<div className="row">
							{advDetails.priceFloatingRatio === null ? (
								<div className="col-4">
									<label htmlFor="price">{`Fixed, ${advDetails.asset}`}</label>
									<div className="input-group text-left">
										<div className="input-group-prepend">
											<button
												className="btn btn-outline-warning btn-sm"
												type="button"
												onClick={() => calculateValueInput("price", -0.01)}
											>
												↓
											</button>
										</div>
										<input
											type="number"
											id="price"
											step="0.1"
											className="form-control form-control-sm"
											value={
												advDetails.price == null
													? ""
													: parseFloat(advDetails.price).toFixed(2)
											}
											onChange={(ev: any) => {
												handlerAdvDetails(ev.target.id, ev.target.value)
											}}
										/>
										<div className="input-group-append">
											<button
												className="btn btn-outline-warning btn-sm"
												type="button"
												onClick={() => calculateValueInput("price", 0.01)}
											>
												↑
											</button>
										</div>
									</div>
								</div>
							) : (
								<div className="col-4">
									<label htmlFor="priceFloatingRatio">Floating, %</label>
									<div className="input-group text-left">
										<div className="input-group-prepend">
											<button
												className="btn btn-outline-warning btn-sm"
												type="button"
												onClick={() =>
													calculateValueInput("priceFloatingRatio", -0.01)
												}
											>
												↓
											</button>
										</div>
										<input
											type="number"
											id="priceFloatingRatio"
											step="0.1"
											className="form-control form-control-sm"
											value={
												advDetails.priceFloatingRatio == null
													? ""
													: parseFloat(advDetails.priceFloatingRatio).toFixed(2)
											}
											onChange={(ev: any) => {
												handlerAdvDetails(ev.target.id, ev.target.value)
											}}
										/>
										<div className="input-group-append">
											<button
												className="btn btn-outline-warning btn-sm"
												type="button"
												onClick={() => calculateValueInput("priceFloatingRatio", 0.01)}
											>
												↑
											</button>
										</div>
									</div>
									{advDetails.priceFloatingRatio !== null ? (
										<div
											className="text-warning text-right d-flex justify-content-between"
											style={{ position: "relative", fontSize: "0.8em" }}
										>
											<span>{`$ ${getCostUSDT(
												calculatedPrice,
												// filterDetails.priceCurrencyUSDT
												+valuationUSDT / +advDetails.surplusAmount
											)}`}</span>
											<span>{`≈ ${getPriceMasked(calculatedPrice)}`}</span>
										</div>
									) : null}
								</div>
							)}
							<div className="col-4">
								<div className="form-label-group text-left">
									<label htmlFor="surplusAmount">{`Amount, ${advDetails.asset}`}</label>
									<input
										name="surplusAmount"
										type="number"
										id="surplusAmount"
										step="0.01"
										className="form-control form-control-sm"
										value={
											advDetails.surplusAmount == null ? "" : advDetails.surplusAmount
										}
										onChange={(ev: any) => {
											if (
												advDetails.tradeType === "SELL" &&
												advDetails.asset === "USDT" &&
												free < 0
											) {
												handlerAdvDetails(ev.target.name, total)
												setVisible(false)
											} else {
												handlerAdvDetails(ev.target.name, ev.target.value)
												setVisible(true)
											}
										}}
									/>
									<div
										className="text-warning text-right d-flex justify-content-between"
										style={{ position: "relative", fontSize: "0.8em" }}
									>
										<span>
											{advDetails.tradeType === "SELL" &&
											advDetails.asset === "USDT" &&
											free > 0 &&
											visible
												? "$ " + free
												: null}
										</span>
										{advDetails.tradeType === "SELL" &&
										// advDetails.asset === "USDT" &&
										visible ? (
											<>
												<span
													className="text-info"
													style={{ cursor: "pointer" }}
													onClick={() => {
														handlerAdvDetails("surplusAmount", total)
														setVisible(false)
													}}
												>
													ALL
												</span>
												<span>{`≈ $${total.toFixed(2)}`}</span>
											</>
										) : (
											<span>{`≈ $${valuationUSDT}`}</span>
										)}
									</div>
								</div>
							</div>
							<div className="col-4">
								<div className="form-label-group text-left">
									<label htmlFor="payUserMethods">{listPayTypeIcons}</label>
									<select
										name="tradeMethods"
										className="form-control form-control-sm"
										onChange={(ev: any) => {
											handlerAdvDetails(ev.target.name, ev.target.value)
										}}
									>
										<option defaultValue="payMethod">payMethod</option>
										{payMethods}
									</select>
								</div>
							</div>
						</div>
						<div className="row mb-3">
							<div className="col-4">
								<div className="form-label-group text-left">
									<label htmlFor="minSingleTransAmount">{`minAmount, ${advDetails.fiatUnit}`}</label>
									<input
										name="minSingleTransAmount"
										type="number"
										id="minSingleTransAmount"
										className="form-control form-control-sm"
										value={
											advDetails.minSingleTransAmount == null
												? ""
												: advDetails.minSingleTransAmount
										}
										onChange={(ev: any) => {
											handlerAdvDetails(ev.target.name, ev.target.value)
										}}
									/>
								</div>
							</div>
							<div className="col-4">
								<div className="form-label-group text-left">
									<label htmlFor="maxSingleTransAmount">{`maxAmount, ${advDetails.fiatUnit}`}</label>
									<input
										name="maxSingleTransAmount"
										type="number"
										id="maxSingleTransAmount"
										className="form-control form-control-sm"
										value={
											advDetails.maxSingleTransAmount == null
												? ""
												: advDetails.maxSingleTransAmount
										}
										onChange={(ev: any) => {
											handlerAdvDetails(ev.target.name, ev.target.value)
										}}
									/>
								</div>
							</div>
							<div className="col-4">
								<button
									name="updateAdv"
									style={{ position: "relative", top: "16px" }}
									className="btn btn-info btn-sm btn-block mt-3"
									type="button"
									onClick={() => {
										if (
											advDetails.tradeType === "SELL" &&
											advDetails.asset === "USDT" &&
											total < 100
										) {
											$("#modal-editAdv_BN").modal("hide")
											handlerPopupWindow(
												"warning",
												"Ops! min AdvAmount must be more than $100"
											)
											startModalAlert()
										} else {
											if (
												advDetails.maxSingleTransAmount !== "" &&
												advDetails.minSingleTransAmount !== "" &&
												advDetails.surplusAmount !== "" &&
												advDetails.tradeMethods.length !== 0 &&
												p2pBalance.length !== 0
											) {
												const objParams = {
													userId,
													exchangeId: id,
													exchangeName: name,
													shortName,
													advDetails: {
														...advDetails,
														initAmount: advDetails.cleanedAmount + current,
													},
													objOrder: {
														page: 1,
														rows: 20,
														fiat: getUserPropertyByExchange("fiat", name, properties),
														asset: getUserPropertyByExchange("asset", name, properties),
														tradeType: getUserPropertyByExchange(
															"tradeType",
															name,
															properties
														),
														transAmount: getUserPropertyByExchange(
															"transAmount",
															name,
															properties
														),
														payTypeList: getUserPropertyByExchange(
															"payTypeList",
															name,
															properties
														),
														quantityPages: getUserPropertyByExchange(
															"quantityPages",
															name,
															properties
														),
													},
												}
												$("#modal-editAdv_BN").modal("hide")
												updateAdv(objParams)
												// console.log(objParams)
											} else {
												handlerPopupWindow("warning", "All fields must be completed")
												startModalAlert()
											}
										}
									}}
								>
									Save Adv
								</button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	)
}

// Редактировние объявления _PX
export const EditAdvModalPX: React.FC<IEditAdvModal> = props => {
	const {
		userId,
		objExchange,
		filterDetails,
		currentCourses,
		p2pBalance,
		merchantPayMethods,
		updateAdv,
		handlerPopupWindow,
		handlerAdvDetails,
		// handlerFilterDetails,
	} = props

	const { advDetails, properties } = filterDetails
	const { id, name, shortName } = objExchange

	const [visible, setVisible] = React.useState(true)

	const calculatedPrice =
		(advDetails.price / 100) * advDetails.priceFloatingRatio

	// подсветка BUY и SELL ордеров
	let classTradeType
	advDetails.tradeType === "BUY"
		? (classTradeType = "success")
		: (classTradeType = "danger")

	// получение суммированного значения input`a
	const calculateValueInput = (elem: any, step: number) => {
		const valueInput: any = $(`#${elem}`).val()
		const summedValue: any = +valueInput + step
		handlerAdvDetails(elem, summedValue)
	}

	let payMethods = null
	const methods = advDetails.tradeMethods
	if (methods) {
		payMethods = merchantPayMethods.map((item: any, index: number) => {
			return (
				<option key={index} value={item.id}>
					{`${item.identifier} id: ${item.id}`}
				</option>
			)
		})
	}

	let listPayTypeIcons: any = (
		<span className="text-danger">No payTypes</span>
	)
	if (methods && methods.length !== 0) {
		listPayTypeIcons = methods.map((item: any, index: number) => {
			return (
				<span key={index} className="icon-pay-dots-filter">
					<img
						src={getUrlIcon("Payment", item.identifier)}
						alt="*"
						title={item.identifier}
						id={item.identifier}
						onClick={(ev: any) => {
							handlerAdvDetails("payTypeRemove", ev.target.id)
						}}
					/>
				</span>
			)
		})
	}

	let total: any = 0
	let current: any = null
	// let initAmount: any = null
	let free: any = null

	// суммарный объём Asset на p2p-Балансе
	const getP2PAssetTotalBalance = (asset: string, arr: any) => {
		let assetBalance
		let digits = 2
		let deviation = 0.01
		for (let i = 0; i < arr.length; i++) {
			if (arr[i].asset === asset) {
				if (asset === "BTC" || asset === "ETH" || asset === "BNB") {
					digits = 5
					deviation = 0.00001
				}
				const freeze = +parseFloat(arr[i].freeze).toFixed(digits)
				const freeBalance = +parseFloat(arr[i].free).toFixed(digits)
				assetBalance = freeze + freeBalance - deviation
			}
		}
		return assetBalance
	}

	if (p2pBalance.length !== 0) {
		// суммарный объём Asset на p2p-Балансе
		total = getP2PAssetTotalBalance(advDetails.asset, p2pBalance)
		// текущий объём в ордере
		current = +parseFloat(advDetails.surplusAmount).toFixed(2)
		// суммарный объём сделок по объявлению
		// initAmount = +parseFloat(advDetails.initAmount).toFixed(2)
		// свободный объём USDT в ордере
		free = (total - current).toFixed(2)
	}

	const valuationUSDT = getValuationUSDT(
		currentCourses,
		advDetails.asset,
		advDetails.surplusAmount
	)

	return (
		<div
			className="modal fade"
			id="modal-editAdv_PX"
			tabIndex={-1}
			role="dialog"
			aria-labelledby="exampleModalCenterTitle"
			aria-hidden="true"
		>
			<div className="modal-dialog modal-dialog-centered" role="document">
				<div className="modal-content">
					<div className={`modal-header alert-${classTradeType}`}>
						<h5 className="modal-title">{`PX | Edit advNo: ${advDetails.adNo}`}</h5>
						<button
							type="button"
							className="close"
							data-dismiss="modal"
							aria-label="Close"
						>
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div className="modal-body">
						<div className="row mb-3">
							{advDetails.priceFloatingRatio === null ? (
								<div className="col-3">
									<div>priceType:</div>
									<div>Fixed</div>
								</div>
							) : (
								<div className="col-3">
									<div>priceType:</div>
									<div className="text-info">Floating</div>
								</div>
							)}
							<div className="col-6">
								<div>tradeType|Asset|Currency</div>
								<div className={`bg-${classTradeType} p-1`}>
									{advDetails.tradeType}
									<span className="icon-pay-dots p-1">
										<img
											src={getUrlIcon("Asset", advDetails.fiatCurrency)}
											className="ml-1"
											alt="-"
											title={advDetails.fiatCurrency}
										/>
										{advDetails.fiatCurrency}
									</span>
									<span className="icon-pay-dots p-1">
										<img
											src={getUrlIcon("Asset", advDetails.asset)}
											className="ml-1"
											alt="-"
											title={advDetails.asset}
										/>
										{advDetails.asset}
									</span>
								</div>
							</div>

							<div className="col-3">
								<div>Status:</div>
								<div>
									{advDetails.adStatus === 1 ? (
										<span className="text-success">Published</span>
									) : (
										<span className="text-warning">Offline</span>
									)}
								</div>
							</div>
						</div>
						<div className="row">
							{advDetails.priceFloatingRatio === null ? (
								<div className="col-4">
									<label htmlFor="price">{`Fixed, ${advDetails.asset}`}</label>
									<div className="input-group text-left">
										<div className="input-group-prepend">
											<button
												className="btn btn-outline-warning btn-sm"
												type="button"
												onClick={() => calculateValueInput("price", -0.01)}
											>
												↓
											</button>
										</div>
										<input
											type="number"
											id="price"
											step="0.1"
											className="form-control form-control-sm"
											value={
												advDetails.price == null
													? ""
													: parseFloat(advDetails.price).toFixed(2)
											}
											onChange={(ev: any) => {
												handlerAdvDetails(ev.target.id, ev.target.value)
											}}
										/>
										<div className="input-group-append">
											<button
												className="btn btn-outline-warning btn-sm"
												type="button"
												onClick={() => calculateValueInput("price", 0.01)}
											>
												↑
											</button>
										</div>
									</div>
								</div>
							) : (
								<div className="col-4">
									<label htmlFor="priceFloatingRatio">Floating, %</label>
									<div className="input-group text-left">
										<div className="input-group-prepend">
											<button
												className="btn btn-outline-warning btn-sm"
												type="button"
												onClick={() =>
													calculateValueInput("priceFloatingRatio", -0.01)
												}
											>
												↓
											</button>
										</div>
										<input
											type="number"
											id="priceFloatingRatio"
											step="0.1"
											className="form-control form-control-sm"
											value={
												advDetails.priceFloatingRatio == null
													? ""
													: parseFloat(advDetails.priceFloatingRatio).toFixed(2)
											}
											onChange={(ev: any) => {
												handlerAdvDetails(ev.target.id, ev.target.value)
											}}
										/>
										<div className="input-group-append">
											<button
												className="btn btn-outline-warning btn-sm"
												type="button"
												onClick={() => calculateValueInput("priceFloatingRatio", 0.01)}
											>
												↑
											</button>
										</div>
									</div>
									{advDetails.priceFloatingRatio !== null ? (
										<div
											className="text-warning text-right d-flex justify-content-between"
											style={{ position: "relative", fontSize: "0.8em" }}
										>
											<span>{`$ ${getCostUSDT(
												calculatedPrice,
												// filterDetails.priceCurrencyUSDT
												+valuationUSDT / +advDetails.remainingAmount
											)}`}</span>
											<span>{`≈ ${getPriceMasked(calculatedPrice)}`}</span>
										</div>
									) : null}
								</div>
							)}
							<div className="col-4">
								<div className="form-label-group text-left">
									<label htmlFor="remainingAmount">{`Amount, ${advDetails.asset}`}</label>
									<input
										name="remainingAmount"
										type="number"
										id="remainingAmount"
										step="0.01"
										className="form-control form-control-sm"
										value={
											advDetails.remainingAmount == null
												? ""
												: advDetails.remainingAmount
										}
										onChange={(ev: any) => {
											if (
												advDetails.tradeType === "SELL" &&
												advDetails.asset === "USDT" &&
												free < 0
											) {
												handlerAdvDetails(ev.target.name, total)
												setVisible(false)
											} else {
												handlerAdvDetails(ev.target.name, ev.target.value)
												setVisible(true)
											}
										}}
									/>
									<div
										className="text-warning text-right d-flex justify-content-between"
										style={{ position: "relative", fontSize: "0.8em" }}
									>
										<span>
											{advDetails.tradeType === "SELL" &&
											advDetails.asset === "USDT" &&
											free > 0 &&
											visible
												? "$ " + free
												: null}
										</span>
										{advDetails.tradeType === "SELL" &&
										// advDetails.asset === "USDT" &&
										visible ? (
											<>
												<span
													className="text-info"
													style={{ cursor: "pointer" }}
													onClick={() => {
														handlerAdvDetails("remainingAmount", total)
														setVisible(false)
													}}
												>
													ALL
												</span>
												<span>{`≈ $${total.toFixed(2)}`}</span>
											</>
										) : (
											<span>{`≈ $${valuationUSDT}`}</span>
										)}
									</div>
								</div>
							</div>
							<div className="col-4">
								<div className="form-label-group text-left">
									<label htmlFor="payUserMethods">{listPayTypeIcons}</label>
									<select
										name="tradeMethods"
										className="form-control form-control-sm"
										onChange={(ev: any) => {
											handlerAdvDetails(ev.target.name, ev.target.value)
										}}
									>
										<option defaultValue="payMethod">payMethod</option>
										{payMethods}
									</select>
								</div>
							</div>
						</div>
						<div className="row mb-3">
							<div className="col-4">
								<div className="form-label-group text-left">
									<label htmlFor="minSingleTransAmount">
										{`minAmount, ${advDetails.fiatCurrency}`}
									</label>
									<input
										name="minSingleTransAmount"
										type="number"
										id="minSingleTransAmount"
										className="form-control form-control-sm"
										value={
											advDetails.minSingleTransAmount == null
												? ""
												: advDetails.minSingleTransAmount
										}
										onChange={(ev: any) => {
											handlerAdvDetails(ev.target.name, ev.target.value)
										}}
									/>
								</div>
							</div>
							<div className="col-4">
								<div className="form-label-group text-left">
									<label htmlFor="maxSingleTransAmount">
										{`maxAmount, ${advDetails.fiatCurrency}`}
									</label>
									<input
										name="maxSingleTransAmount"
										type="number"
										id="maxSingleTransAmount"
										className="form-control form-control-sm"
										value={
											advDetails.maxSingleTransAmount == null
												? ""
												: advDetails.maxSingleTransAmount
										}
										onChange={(ev: any) => {
											handlerAdvDetails(ev.target.name, ev.target.value)
										}}
									/>
								</div>
							</div>
							<div className="col-4">
								<button
									name="updateAdv"
									style={{ position: "relative", top: "16px" }}
									className="btn btn-info btn-sm btn-block mt-3"
									type="button"
									onClick={() => {
										if (
											advDetails.tradeType === "SELL" &&
											advDetails.asset === "USDT" &&
											total < 100
										) {
											$("#modal-editAdv_PX").modal("hide")
											handlerPopupWindow(
												"warning",
												"Ops! min AdvAmount must be more than $100"
											)
											startModalAlert()
										} else {
											if (
												advDetails.maxSingleTransAmount !== "" &&
												advDetails.minSingleTransAmount !== "" &&
												advDetails.remainingAmount !== "" &&
												// p2pBalance.length !== 0 &&
												advDetails.tradeMethods.length !== 0
											) {
												const objParams = {
													userId,
													exchangeId: id,
													exchangeName: name,
													shortName,
													advDetails: {
														...advDetails,
														// price: advDetails.price, // "33757.02",
														initAmount: parseFloat(advDetails.remainingAmount).toFixed(
															8
														),
														remainingAmount: parseFloat(
															advDetails.remainingAmount
														).toFixed(8),
														priceFloatingRatio: parseFloat(
															advDetails.priceFloatingRatio
														).toFixed(8),
														minSingleTransAmount: advDetails.minSingleTransAmount, // "1000",
														maxSingleTransAmount: advDetails.maxSingleTransAmount, // "55000",
													},
													objOrder: {
														page: 1,
														rows: 20,
														fiat: getUserPropertyByExchange("fiat", name, properties),
														asset: getUserPropertyByExchange("asset", name, properties),
														tradeType: getUserPropertyByExchange(
															"tradeType",
															name,
															properties
														),
														transAmount: getUserPropertyByExchange(
															"transAmount",
															name,
															properties
														),
														payTypeList: getUserPropertyByExchange(
															"payTypeList",
															name,
															properties
														),
														quantityPages: getUserPropertyByExchange(
															"quantityPages",
															name,
															properties
														),
													},
												}
												$("#modal-editAdv_PX").modal("hide")
												updateAdv(objParams)
												// console.log(objParams)
											} else {
												handlerPopupWindow("warning", "All fields must be completed")
												startModalAlert()
											}
										}
									}}
								>
									Save
								</button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	)
}
